<?php
/**
 * Created by JiangJiaCai.
 * User: Administrator
 * Date: 2017/12/14 0014
 * Time: 10:23
 */

namespace App\Http\Controllers;
//{use template}
use com_jjcbs\lib\ApiJson;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 规范 data={},sign=''
 * Base ApiController
 * Class BaseApiController
 * @package App\Http\Controllers
 */
class BaseApiController
{
    use ApiJson,ValidatesRequests;
    //{method template}

    const SIGN_KEY = 'c254e360e9de4a3b53cda29959979734';
    /**
     * the request param
     * @var array
     */
    protected $param = [];
    public function __construct(Request $request)
    {
//{construct template}
        try{
            $this->validate($request , [
                'sign' => 'required',
                'data' => 'required'
            ]);
            $this->param = json_decode($request->get('data') , true);
            if ( !$this->checkSign($request->get('sign')) ) return $this->setJsonError('sign error');
        }catch (\Exception $e){
            Log::error('sign错误' . $e->getMessage());
            return $this->echoJson($this->setJsonError('系统错误！' . $e->getMessage()));
        }
    }

    /**
     * check sign is sure
     * @param string $sign
     * @return bool
     */
    private function checkSign(string $sign = '') : bool{
        ksort($this->param);
        $str = '';
        foreach ($this->param as $k => $v){
            if ( empty($v)) continue;
            $str .= $k . $v;
        }
        return  md5(sha1(urlencode($str)) . self::SIGN_KEY) === $sign;
    }
}